<?php

/*
 * This will be the Create Department-Position page. 
 * 
 * Created by: Peter Agno Jr.
 * Date created: November 29, 2011
 */

    include("siteTop.php"); 
    include('includes/siteConfig.php'); 

    // connect to database
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
?>

<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){   
            var rowSecGrp = 0; // variable for the number of security groups of the position
            
            jQuery("#addPosId").focus();
            
            // CHANGE FIRST THE CSS OF THE NAV BAR
            jQuery("#adminTools-nav").addClass("highlightMenuBar");
            jQuery("#orgSetup-nav").addClass("highlightMenuBar");
            jQuery("#posSetup-nav").addClass("highlightMenuBar");
            
            dispPositions("fromBase");  // Updates the position onload
            addPosSecGrpRow(); // Add a position's security group row
            
            // Start - Add another row in Position's Security Group Screenlet
            jQuery('#addSecGrpBtn').live("click",function() {
                addPosSecGrpRow();
            }); // End - Add another row in Position's Security Group Screenlet
            
            // Start - Remove a security group row
            jQuery('.removeSecGrpBtn').live("click",function() {
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                jQuery("#rowSecGrpId_"+tempSubstr[1]).remove();
                
                // Add a department row if the table row is equal to 1 (header's row)
                if ( jQuery('#posSecGrpTable tr').length == 2 ) {
                    jQuery("#addSecGrpBtn").click();
                }
            }); // End - Remove a security group row
            
            // Start - Change positions depending on the departmentId being set
            jQuery(".deptDrpDwn").live("change",function() {
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                dispPositions(tempSubstr[1]);
            }); // End - Change positions depending on the departmentId being set
            
            // Start - Go back to admDeptPosSetup.php
            jQuery('#admDeptPosStpBtn').live("click",function() {
                window.location = 'admDeptPosSetup.php';
            }); // End - Go back to admDeptPosSetup.php 
            
            // Start - create department-position
            jQuery('#createDeptPosButton').live("click",function() {
                if ( jQuery(".deptDrpDwn").val() == "selctDept" ) {
                    alert("Error : Please select a department name.");
                }
                else if ( jQuery(".posRadioBtn:checked").val() == "existPos" && jQuery("#posDrpDwn_fromBase").val() == "selectPos" ) {
                    alert("Error : Please select a position name.");
                }
                else if ( jQuery(".posRadioBtn:checked").val() == "addPos" && ( jQuery("#addPosId").val() == "" ||  jQuery("#addPosName").val() == "" ) ) {
                    alert("Error : Please fill up Position Information.");
                }
                else if ( noSameSecGrp() != true ) {
                    alert("Error : There should be no same security group.");
                }
                else {
                    var secGrpIds = "";
                    // Get each of the value of secGrpId
                    jQuery('.secGrpId').each(function(index) {
                        secGrpIds += jQuery('#' + this.id).val() + ",";
                    });
                    
                    // Set positionFlag if it is existing or add new
                    if ( jQuery(".posRadioBtn:checked").val() == "existPos" ) {
                        positionFlag = "existPos";
                    }
                    else {
                        positionFlag = "addPos";
                    }

                    // Start - Ajax the creating of department-position                    
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admCreateDeptPos.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            departmentId : jQuery("#deptDrpDwn_fromBase").val(),
                            positionId : jQuery("#posDrpDwn_fromBase").val(),
                            departmentName : jQuery("#deptDrpDwn_fromBase :selected").text(),
                            positionName : jQuery("#posDrpDwn_fromBase :selected").text(),
                            secGrpIds : secGrpIds,
                            positionFlag : positionFlag,
                            addPosId : jQuery("#addPosId").val(),
                            addPosName : jQuery("#addPosName").val()
                        },
                        success : function(data){
                            // If, successful creation of department-position
                            if (data) {
                                if ( data[0].flag == "success" ) {
                                    jQuery("#deptPosSuccessMessage").val(data[0].msg);
                                    jQuery("#deptPosStpMsgForm").submit();
                                }
                                else {
                                    alert(data[0].msg);
                                }
                            } // End if, successful creation of department-position
                        },
                        error : function() {
                            alert("Error : Creating the position was not successful.");
                        }
                    }); // End - Ajax the creating of department-position
                } // End else
            }); // End - create department-position
            
            // Start - Check the clicked posRadioBtn
            jQuery('.posRadioBtn').live("click",function() {
                jQuery('.posRadioBtn').attr('checked', false);
                jQuery(this).attr('checked', true);
                
                if ( this.id == "existPos" ) {
                    jQuery(".posTr").show();
                    jQuery(".addPosTr").hide();
                }
                else {
                    jQuery(".posTr").hide();
                    jQuery(".addPosTr").show();
                    jQuery("#addPosId").focus();
                }
            }); // End - Check the clicked posRadioBtn
            
            // Start - Function: Check if there is same security group in Position's Security Group Screenlet
            function noSameSecGrp() {
                noSame = true;
                
                if ( jQuery('#posSecGrpTable tr').length == 3 ) {
                    return noSame;
                }
                else {
                    for( x = 1 ; x <= rowSecGrp && noSame == true ; x++ ){
                        for( y = 1 ; y <= rowSecGrp && noSame == true ; y++ ){
                            if ( x != y ) {
                                if ( jQuery("#secGrpId_"+x).val() == jQuery("#secGrpId_"+y).val() && jQuery("#secGrpId_"+x).val() != undefined && jQuery("#secGrpId_"+y).val() != undefined  ) {
                                    noSame = false;
                                }
                            }
                        }
                    }
                    
                    return noSame;
                }
            } // End - Function: Check if there is same security group in Position's Security Group Screenlet
            
            // Start - Ajax the positions
            function dispPositions(scrnPostn) {
                
                if ( jQuery("#deptDrpDwn_"+scrnPostn).val() == "selctDept") {
                    jQuery("#deptPosScrnlt").text("Please select a department name");
                }
                else {
                    jQuery("#deptPosScrnlt").text(jQuery("#deptDrpDwn_"+scrnPostn+" :selected").text()+" Department Positions");
                }
                
                // If the document id is not selctDept
//                if ( jQuery("#deptDrpDwn_"+scrnPostn).val() != "selctDept" ) {
//                    jQuery(".quesPosTr").show();
//                    jQuery('.posRadioBtn').attr('checked', false);
//                    hidePosInfo();
//                    jQuery('#existPos').attr('checked', true);  // Check the radio button of existPos
//                    jQuery('.posTr').show();    // Show position dropdown
//                    jQuery(".divSecGrp").show();    // Show the security group screenlet
                    
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/admGetFilteredPos.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            departmentId : jQuery("#deptDrpDwn_"+scrnPostn).val()
                        },
                        success : function(data){
                            jQuery("#deptPosTable").children().remove();
                            
                            if (data) {
                                if ( data == null ) {
                                    // Perform this if no data was querried
                                    varRow = "<tr><td colspan='2'><span class='errorMessage'>No positions found.</span></td></tr>";
                                    jQuery("#deptPosTable").append(varRow);
                                }
                                else {
                                    // REMOVE THE CHILDREN OF posDrpDwn DROPDOWN
    //                                jQuery("#posDrpDwn_"+scrnPostn).children().remove();
    //                                jQuery("#posDrpDwn_"+scrnPostn).append("<option value='selectPos'>Select Position Name</option>");
    //
    //                                jQuery.each(data, function(index, data) {
    //                                    jQuery("#posDrpDwn_"+scrnPostn).append("<option value='"+data.positionId+"'>"+data.positionName+"</option>");
    //                                });

                                    jQuery("#deptPosTable").append("<tr><th>Position Id</th><th>Position Name</th></tr>");

                                    jQuery.each(data, function(index, data) {
                                        jQuery("#deptPosTable").append("<tr><td>"+data.positionId+"</td><td>"+data.positionName+"</td></tr>");
                                    });
                                }
                            }
                            else {
                                varRow = "<tr><td colspan='2'><span class='errorMessage'>No positions found.</span></td></tr>";
                                jQuery("#deptPosTable").append(varRow);
                            }
                        },
                        error : function() {
                            alert("Error in getting the positions.");
                        }
                    });
                
//                } // End If the document id is not selctDept
//                else {
//                    jQuery(".quesPosTr").hide();
//                    hidePosInfo();
//                    jQuery(".divSecGrp").hide();    // Hide the security group screenlet
//                }
            } // End - Ajax the positions
            
            // Start - Hide neccessary information
            function hidePosInfo() {
                jQuery('.posTr').hide();
                jQuery('.addPosTr').hide();
                jQuery("#addPosId").val("");
                jQuery("#addPosName").val("");
            } // End - Hide neccessary information
            
            // Start - Function: Add another row in Position's Security Group Screenlet
            function addPosSecGrpRow() {
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getSecGroupList.php',
                    dataType : 'json',
                    async : false,
                    data: {
                    },
                    success : function(data){
                        if (data) {
                            secGrpRow = "";
                            rowSecGrp++;
                            secGrpRow += "<tr id='rowSecGrpId_"+rowSecGrp+"'>";

                            // Prepare the Security Group dropdown
                            secGrpRow += "<td><select name='secGrpId' id='secGrpId_"+rowSecGrp+"' class='secGrpId'>";
                                
                            jQuery.each(data, function(index, data) {
                                secGrpRow += "<option value='"+data.securityGroupId+"'>"+data.securityGroupName+"</option>";
                            });
                            
                            secGrpRow += "</select></td>";    // Close the Security Group dropdown
                                
                            // Prepare the Remove button
                            secGrpRow += "<td><input type='Submit' name='removeSecGrpBtn' id='removeSecGrpBtn_"+rowSecGrp+"' value='Remove' class='siteRedButton removeSecGrpBtn' /></td>";
                            secGrpRow += "</tr>"; // Close the row
                            jQuery(".secGrpAddRow").before(secGrpRow);    // Append the row
                        } 
                    },
                    error : function() {
                        alert("Error : Adding security group row was not successful.");
                    }
                });
            } // End - Function: Add another row in Position's Security Group Screenlet
            
        }); // End - jQuery document ready
    </script>
<!-- HEAD END -->

<div id="content">
<h1>Create Position</h1>
    <div class="contentbox">       
        <?php
        // Check permission
        $thePermissions = array('DEPTSTP', 'POSSTP');
        if ( checkPermission( $thePermissions, $userId ) == true ) {
        ?>
            <span class="screenlet" >Position Information</span>
            <table>
                <tr>
                    <td>Department Name : </td>
                    <td>
                        <select name='deptDrpDwn_fromBase' id='deptDrpDwn_fromBase' class='deptDrpDwn'>
                        <?php
                            // Insert 'All' first
                            echo "<option value='selctDept'>Select Department Name</option>";
                        
                            $deptQuery =
                                "
                                    SELECT departmentId, departmentName
                                    FROM Department
                                    ORDER BY departmentName
                                ";

                            $deptResult = mysql_query($deptQuery) or die ('Error in query: $deptQuery. ' . mysql_error());
                        
                            while ( $deptRow = mysql_fetch_array($deptResult) )
                                echo "<option value='".$deptRow['departmentId']."'>".$deptRow['departmentName']."</option>";
                        
                            mysql_free_result($deptResult);
                        ?>
                        </select>
                    </td>
                </tr>
                
                <!-- For question of position -->
                <tr class='quesPosTr' style="display:none;">
                    <td>Choose Position : </td>
                    <td>
                        <input type="radio" id="existPos" value="existPos" class="posRadioBtn"/> Existing Position
                    </td>
                </tr>
                <tr class='quesPosTr' style="display:none;">
                    <td></td>
                    <td>
                        <input type="radio" id="addPos" value="addPos" class="posRadioBtn" checked /> Add Position
                    </td>
                </tr>
                
                <!-- Adding new position tr -->
                <tr class='addPosTr' style="display:none;">
                    <td> &nbsp </td>
                    <td></td>
                </tr>
                <tr class='addPosTr' style="display:none;">
                    <td><strong>New Position Information</strong></td>
                    <td></td>
                </tr>
                <tr class='addPosTr'>
                    <td>Position ID : </td>
                    <td><input type="text" id="addPosId" value=""/></td>
                </tr>
                <tr class='addPosTr'>
                    <td>Position Name : </td>
                    <td><input type="text" id="addPosName" value=""/></td>
                </tr>
                
                <!-- Adding existing position tr -->
                <tr class='posTr' style="display:none;">
                    <td>Position Name : </td>
                    <td>
                        <select name='posDrpDwn_fromBase' id='posDrpDwn_fromBase'>
<!--                            <option value="All">All</option>-->
                        </select>
                    </td>
                </tr>
            </table>
            
            <span class="screenlet" ><span id="deptPosScrnlt"></span></span>
            <table border="1" id="deptPosTable" width="40%">

            </table>
            
            <div class="divSecGrp">
                <span class="screenlet" >Select Security Groups</span>
                <table border="1" id="posSecGrpTable">
                    <tr>
                        <th>Security Group Name</th>
                        <th></th>
                    </tr>
                    <tr class="secGrpAddRow">
                        <th></th>
                        <th><input type="Submit" name="addSecGrpBtn" id="addSecGrpBtn" value="Add" class="siteGreenButton" /></th>
                    </tr>
                </table>
            </div>
            
            <input type="Submit" name="createDeptPosButton" id="createDeptPosButton" value="Create" class="siteGreenButton" />
            <input type="Submit" name="admDeptPosStpBtn" id="admDeptPosStpBtn" value="Cancel" class="siteRedButton" />
            
            <!-- Hidden form to be used when the creation of department-position was successful -->
            <form id="deptPosStpMsgForm" name="deptPosStpMsgForm" action="admDeptPosSetup.php" method="POST">
                <input type="hidden" name="deptPosSuccessMessage" id="deptPosSuccessMessage" value=""/>
            </form>
        <?php
        }
        else {
            echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
        }
        // End checking permission
        ?>
    </div> <!-- contentbox end div -->
    <div style="position:relative; visibility: hidden">end</div>    <!-- extra space for contentbox -->
</div> <!-- content end div -->
<?php
    include ("siteBottom.php"); 
?>

